package com.taiyuan.tongcheng.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.acl.LastOwnerException;
import java.text.DecimalFormat;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.DensityUtils;
import org.kymjs.kjframe.utils.KJLoger;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.taiyuan.tongcheng.adapter.CarKindAdapter;
import com.taiyuan.tongcheng.adapter.OderStationAdapter;
import com.taiyuan.tongcheng.adapter.PayKindAdapter;
import com.taiyuan.tongcheng.application.TCBroadcastAction;
import com.taiyuan.tongcheng.bean.BjExtraServiceInfo;
import com.taiyuan.tongcheng.bean.CargoOrderSimple;
import com.taiyuan.tongcheng.bean.CargoPrice;
import com.taiyuan.tongcheng.bean.StaListData;
import com.taiyuan.tongcheng.bean.ZcExtraServiceInfo;
import com.taiyuan.tongcheng.http.HttpParamUtil;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.util.ACache;
import com.taiyuan.tongcheng.widget.dialog.TcBuilder;
import com.tytc56.user.R;


public class ExpressOrderActivity extends BaseActivity{
//	widget basic信息
	@BindView(id=R.id.tv_order_time)
	private TextView orderTimeTv;
	@BindView(id=R.id.tv_order_car)
	private TextView carStyleTv;
	@BindView(id=R.id.tv_order_service)
	private TextView serviceTv;
	@BindView(id=R.id.tv_order_paystyle)
	private TextView payStyleTv;
	@BindView(id=R.id.tv_order_addinfo)
	private TextView addNoteTv;
//	list起点途径点信息
	@BindView(id=R.id.lv_sta_order)
	private ListView stationLv;
	//price价格
	@BindView(id =R.id.tv_all_price)
	private TextView  allPriceTv;
	@BindView(id =R.id.tv_price_start)
	private TextView  startPriceTv;
	@BindView(id =R.id.tv_price_km)
	private TextView  kmPriceTv;
	@BindView(id =R.id.tv_price_service)
	private TextView  servicePriceTv;
	@BindView(id=R.id.tv_price_coupon)
	private TextView couPonPrice;
	@BindView(id=R.id.tv_price_start_lable)
	private TextView  startPriceLable;
	@BindView(id=R.id.tv_price_ninght_lable)
	private TextView  ninghtPriceLable;
	@BindView(id=R.id.tv_price_night_cargo)
	private TextView  ninghtPrice;
	@BindView(id=R.id.tv_price_km_lable)
	private TextView  lichengPriceLable;
	@BindView(id=R.id.tv_price_tujind)
	private TextView  tujindianPriceTv;
	@BindView(id=R.id.tv_service_price_detail)
	private TextView  detailPriceTv;

	//price
	private double startPrice;
	private double kmPrice;
	private double servicePrice;
	//下单按钮
	@BindView(id=R.id.btn_oder,click=true)
	private Button  orderBtn;
	
	//实体类
	private CargoOrderSimple cargoSimple=new CargoOrderSimple();
	private CargoPrice       cargoPrice;
	private StaListData  stationData=new StaListData();
	//
	private OderStationAdapter  adapter;
	private IntentFilter intentFilter;
	private List<String> serviceListString;
	//
	private Dialog  tcYYokDialog;
	
	@Override
	public void setRootView() {
       setContentView(R.layout.activity_express_order);		
	}
	@Override
	public void initWidget() {
		super.initWidget();
		initView();
		topTv.setText("确认信息");
		rightTv.setVisibility(View.GONE);
	}
	
	@Override
		public void widgetClick(View v) {
			super.widgetClick(v);
			switch (v.getId()) {
			case R.id.btn_oder:
				TcLoaddingDialog.show();
				makeOrder();
				break;
			default:
				break;
			}
			
		}
	
	@Override
	public void initData() {
		super.initData();
		initReceiver();
		cargoSimple=(CargoOrderSimple)ACache.get(getApplicationContext()).getAsObject("CARGO");
		KJLoger.debug("cargo im"+cargoSimple.getIsImFalg());
		
		
		//初始化basic信息
		orderTimeTv.setText(cargoSimple.getErviceDate());
		carStyleTv.setText(CarKindAdapter.carName[cargoSimple.getTruckTypeId()-1]);
//		serviceTv.setText(getCarservice());
		payStyleTv.setText(PayKindAdapter.payName[cargoSimple.getPayTypeId()-1]);
		if(cargoSimple.getNote()==null||cargoSimple.getNote().equals("")){

			addNoteTv.setText("无");
		}else{
			addNoteTv.setText(cargoSimple.getNote());
		}
		KJLoger.debug(cargoSimple.getMiddlePlaceInfo());
		//途径点信息
		stationData=(StaListData)ACache.get(getApplicationContext()).getAsObject("ALLSTA");
		LinearLayout.LayoutParams haltLisfLp =(LayoutParams)stationLv.getLayoutParams();
		haltLisfLp.height=stationData.getStationList().size()* (DensityUtils.dip2px(this, 40)+1);
		stationLv.setLayoutParams(haltLisfLp);
		//途径点信息
		adapter= new OderStationAdapter(this, stationData.getStationList());
		stationLv.setAdapter(adapter);
		//价格信息
		cargoPrice=(CargoPrice)ACache.get(getApplicationContext()).getAsObject(ExpressActivity.TAG_ORDER_PRICE);
	    refreashPrice();
	
	}
	
	 /**
    * @Description: 监听1下单成功广播2 刷新服务项广播
    * @return void
    * @throws
    * @autour wzq
    * @date 2015-9-5 下午3:31:47
    * @update (date)
     */
	private void initReceiver() {
		intentFilter = new IntentFilter();
		intentFilter.addAction(TCBroadcastAction.SUCCESS_MAKE_ORDER);
		registerReceiver(receiver, intentFilter);

	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			
			if(TCBroadcastAction.SUCCESS_MAKE_ORDER.equals(intent.getAction())){
				ExpressOrderActivity.this.finish();
			}
		}
	};
	
	
	/**
	 * 
	* @Description: 获取服务字符串
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-8-31 上午10:05:20
	* @update (date)
	 */
	private String getCarservice() {
		StringBuilder builder =new StringBuilder();
		String[] serviceItem = getResources().getStringArray(R.array.cargo_service);
		
		if(cargoSimple.getServiceidList().size()>0){
			for (int i = 0; i < cargoSimple.getServiceidList().size(); i++) {
				builder.append(serviceItem[cargoSimple.getServiceidList().get(i)-1]);
				builder.append("、");
			}
			builder.deleteCharAt(builder.lastIndexOf("、"));
		}else{
			builder.append("无");
		}
		return builder.toString();
	}
	
    //刷新价格
	private void refreashPrice() {
		
		serviceListString=JSON.parseArray(cargoPrice.getServiceListInfo(), String.class);
    	for (String serviceString: serviceListString) {
			ZcExtraServiceInfo  serviceInfo =JSON.parseObject(serviceString, ZcExtraServiceInfo.class);
			KJLoger.debug(serviceInfo.toString());
    	}
    	
		DecimalFormat df = new DecimalFormat("0.0");
		startPriceLable.setText(getString(R.string.lable_price_start)+"(含"+cargoPrice.getStartKm()+"公里)");
	    startPrice=cargoPrice.getStartPrice();
		servicePrice=(cargoPrice.getExtraServicePrice());
		startPriceTv.setText("￥"+startPrice);
		kmPriceTv.setText("￥"+cargoPrice.getLiChengPrice()+"");
		servicePriceTv.setText("￥"+servicePrice+"");
		if(cargoPrice.getTotalKmNum()>cargoPrice.getStartKm()){
			lichengPriceLable.setText(getString(R.string.lable_price_km)+"("+df.format(cargoPrice.getTotalKmNum()-cargoPrice.getStartKm())+"X"+cargoPrice.getUnitPrice()+"/公里)");
		}else{
			lichengPriceLable.setText(getString(R.string.lable_price_km));
		}
		allPriceTv.setText("￥"+cargoPrice.getTotalMoney());
		couPonPrice.setText("￥ -" +cargoSimple.getCouponPrice());
		ninghtPrice.setText("￥"+cargoPrice.getNightServicePrice());
		if(cargoPrice.getMiddlePlaceCount()>0){
			tujindianPriceTv.setText("￥"+cargoPrice.getMiddlePlaceCount()*cargoPrice.getMiddlePlaceUnitPrice()+"("+cargoPrice.getMiddlePlaceCount()+"*"+cargoPrice.getMiddlePlaceUnitPrice()+")");
		}else{
			tujindianPriceTv.setText("￥ 0");
		}
		
		//=========增加服务详情20151108=================
		if(cargoPrice.getExtraServicePrice()>0){
			serviceListString=JSON.parseArray(cargoPrice.getServiceListInfo(), String.class);
			StringBuilder builder=new StringBuilder();
	    	for (String serviceString: serviceListString) {
				ZcExtraServiceInfo  serviceInfo =JSON.parseObject(serviceString, ZcExtraServiceInfo.class);
				builder.append(serviceInfo.getName()+"("+serviceInfo.getPrice()+")");
				builder.append("、");
	    	}
	    	builder.deleteCharAt(builder.lastIndexOf("、"));
//	    	builder.append("合计："+cargoPrice.getExtraServicePrice());
	    	serviceTv.setText(builder.toString());
		}else{
			serviceTv.setText(getCarservice());
		}
		
	}
	/**
	 * 
	* @Description: 用户下单
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-8-31 上午11:48:15
	* @update (date)
	 */
	private void makeOrder() {
		
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjh = new KJHttp(config);
		HttpParams params = new HttpParams();
		params=HttpParamUtil.getMakeExpressOrderParam(ExpressOrderActivity.this, cargoSimple, cargoPrice,spUtil);
		KJLoger.debug(params.getUrlParams().toString());
		kjh.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.FREIGHT_MAKE_ORDER, params,
             new HttpCallBack() {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);

						String str;
						try {
							str = URLDecoder.decode(new String(t), "UTF-8");
							KJLoger.debug(str);
							WebData webData = TcJsParser.getWedataData(str);
							if (webData.getStatus() == 1) {
								if(TcLoaddingDialog.isShowing()){
									TcLoaddingDialog.dismiss();
								}
                                JSONObject js;
								try {
									js = new JSONObject(webData.getData());
									String msgId=js.optString("returnId", "");
									spUtil.setCacheOrderId(msgId);
									int msgImFlag=js.optInt("isImFalg",1);
									if (msgImFlag == 1) {
										startActivity(ExpressOrderIngActivity.class);
										sendBroadcast(new Intent(
												TCBroadcastAction.SUCCESS_MAKE_ORDER));
									}else{
										tcYYokDialog=TcBuilder.getInstance(ExpressOrderActivity.this,1)
												.withTitle("提示")
												.withContent("您的订单信息已经受理，您可以在我的订单中看到改订单的状态，并进行订单操作，是否前往？")
												.withButton1Text("确定").withButton2Text("取消")
												.setButton1Click(new OnClickListener() {
											
											@Override
											public void onClick(View v) {
												Bundle bundle=new Bundle();
												bundle.putInt(OrderActivity.TAG_FROM, OrderActivity.TAG_FROM_CARGO);
												startActivity(OrderActivity.class,bundle);
												sendBroadcast(new Intent(
														TCBroadcastAction.SUCCESS_MAKE_ORDER));
												ExpressOrderActivity.this.finish();
												tcYYokDialog.cancel();
											
											}
										}).setButton2Click(new OnClickListener() {
											
											@Override
											public void onClick(View v) {

												sendBroadcast(new Intent(
														TCBroadcastAction.SUCCESS_MAKE_ORDER));
												tcYYokDialog.cancel();
											
											}
										});
										tcYYokDialog.show();
										
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
								
								showCustomToast(webData.getMsg());
							} else {
								showCustomToast(webData.getMsg());
							}
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}
					
					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
						if (errorNo == -1) {
							// 网络超时
							ViewInject.toast(strMsg);
						}
					}
				});
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}

}
